/*
 * Copyright 2011 Clean GWT
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
package com.cleangwt.page.client;

import static com.google.gwt.dom.client.Style.Unit.PX;

import com.google.gwt.dom.client.Style;
import com.google.gwt.dom.client.Style.Position;
import com.google.gwt.event.logical.shared.ResizeEvent;
import com.google.gwt.event.logical.shared.ResizeHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.ProvidesResize;
import com.google.gwt.user.client.ui.RequiresResize;
import com.google.gwt.user.client.ui.Widget;

/**
 * A {@link PageContainer} implementation that implements {@link ProvidesResize} and automatically
 * delegates that interface's methods to its wrapped widget, which must itself implement
 * {@link RequiresResize}.
 * 
 * <p>
 * This panel automatically calls {@link RequiresResize#onResize()} on its wrapped widget when
 * initially created, and whenever the window is resized.
 * </p>
 * 
 * @author Jess
 * @version 1.0
 * @since 1.0
 */
public abstract class ResizePageContainer extends Composite implements PageContainer,
    ProvidesResize {

  private HandlerRegistration resizeRegistration;

  @Override
  protected void initWidget(Widget widget) {
    assert widget instanceof RequiresResize : "ResizePageContainer requires that its wrapped widget implement RequiresResize";
    super.initWidget(widget);
  }

  @Override
  protected void onLoad() {
    super.onLoad();
    // fill parent
    Style style = getElement().getStyle();
    style.setPosition(Position.ABSOLUTE);
    style.setLeft(0, PX);
    style.setTop(0, PX);
    style.setRight(0, PX);
    style.setBottom(0, PX);

    resizeRegistration = Window.addResizeHandler(new ResizeHandler() {
      public void onResize(ResizeEvent event) {
        ((RequiresResize) getWidget()).onResize();
      }
    });

  }

  @Override
  protected void onUnload() {
    super.onUnload();
    resizeRegistration.removeHandler();
    resizeRegistration = null;
  }

}